package org.hepeng.workx.spring.cloud.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

/**
 * @author he peng
 */
public class HeaderCopyingFeignRequestInterceptor implements RequestInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(HeaderCopyingFeignRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)) {
            HttpServletRequest httpRequest = requestAttributes.getRequest();
            Enumeration<String> headerNames = httpRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = httpRequest.getHeader(headerName);
                template.header(headerName , headerValue);

                LOG.debug("http request header copying , name {} , value {} " , headerName , headerValue);
            }
        } else {
            LOG.warn("Unable to copy http request header , cause ServletRequestAttributes is null");
        }
    }
}
